let Iv = [], count = 0;
let srcS = [ //---储存动画信息
    {
        id: "eat", //---ID
        src: "common/images/eat/eat_", //---路径前段
        len: 40, //---图片数
        setInt: 90, //---定时器间隔(ms)
        width: 640, //---图片的尺寸
        height: 1024,
        x: 0, //---相对于画布左上角的X坐标
        y: 0, //---相对于画布左上角的Y坐标
        format: '.jpg'
    },
    {
        id: "knock",
        src: "common/images/knockOut/knockout_",
        len: 80,
        setInt: 90,
        width: 640,//640
        height: 1024,//1024
        x: 0,
        y: 0,
        format: '.jpg'
    },
]

function imgLoad(obj, cb) { //----预加载
    let imgArray = []; //---存储Image对象
    let len = obj.len;
    for (let i = 0; i < len; i++) {
        let j = '0';
        if (i > 9) j = '';
        let str = j + i.toString();
        let img = new Image();
        img.src = obj.src + str + obj.format; //---设置Image对象路径，这里图片的路径编号是00,01,02...10...39
        imgArray.push(img);
    }
    cb(imgArray, len, obj.x, obj.y, obj.width, obj.height, obj.setInt); //---回调函数中传递参数
}

function Action(obj, ctx) { //---动画播放
    return new Promise((resolve) => { //---采用Promise进行播放动画，执行完再释放线程，避免多次点击播放造成混乱
        let i = 0, x, y, w, h;
        let len, imgArray, interval;
        imgLoad(obj, (imgArray_, len_, x_, y_, w_, h_, interval_) => {
            console.info("预加载完毕");
            imgArray = imgArray_; //---设置drawImage参数
            len = len_;
            x = x_;
            y = y_;
            w = w_;
            h = h_;
            interval = interval_;

            Iv[count++] = setInterval(() => { //---定时器
                if (i < len) {
                    if (i !== 0)ctx.clearRect(x, y, w, h); //---不断绘制新图，清除旧图
                    ctx.drawImage(imgArray[i], x, y, w, h);
                    ++i;
                } else {
                    ctx.drawImage(imgArray[len - 1], x, y, w, h); //---可选择保留结尾动作
                    clearInterval(Iv[count - 1]); //---清除定时器，动画结束
                    resolve("false");
                }
            }, interval);
        })
    })
}

function selectInfo(id, cb) { //---找到对应的动画对象
    let obj = srcS.find(e => e.id === id);
    if(!obj){
        console.info('cannot find the certain info')
        return
    }
    else cb(obj);
}

export function ActionReady(id, ctx) { //---封装接口
    let obj;
    selectInfo(id, (obj_) => {
        obj = obj_;
    })
    return Action(obj, ctx);
}

